#!/bin/bash

# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2020-present Shanti Gilbert (https://github.com/shantigilbert)

# Source predefined functions and variables
. /etc/profile

function error() {
	ERROR=$(cat /tmp/logs/exec.log)

	/usr/bin/error.sh
}

function audio() {
	# This has to be expanded to check for new GLX devices running on Amlogic-ng,
	# but right now its mostly used on ES to change audio to alsa before launching or else ES hangs on GXL devices.
   if [[ "$1" == "alsa" ]]; then
		set_audio alsa
   elif [[ "$1" == "pulse" ]]; then
		set_audio pulseaudio
   else
		set_audio auto
   fi
}

function devilutionx_setup() {
	grep "Phone Book" /storage/.local/share/diasurgical/devilution/diablo.ini &>/dev/null
	if [ ! "$?" == 0 ]
	then
		mkdir -p /storage/.local/share/diasurgical/devilution &>/dev/null ||:
		cat <<EOF >>/storage/.local/share/diasurgical/devilution/diablo.ini
[Phone Book]
Entry1=
Password1=
EOF
	fi
}

function devilutionx_server() {
	devilutionx_setup
	sed -i 's#^Entry1.*$#Entry1='$1'#' /storage/.local/share/diasurgical/devilution/diablo.ini &>/dev/null
}

function devilutionx_password() {
	devilutionx_setup
        sed -i 's#^Password1.*$#Password1='$1'#' /storage/.local/share/diasurgical/devilution/diablo.ini &>/dev/null
}

function identity_backup() {
	if [ "$(pgrep emulationstation)" ]
	then
		systemctl stop emustation
		EMURESTART=true
	fi
	echo -en '\e[20;0H\e[37mPlease wait, backing up identity data...\e[0m' >/dev/console
        BPATH="/storage/roms/backup/"
	mkdir -p "${BPATH}"
        IDENTITYFILE="${BPATH}/identity.tar.gz"
        tar -cvzf ${IDENTITYFILE} /storage/.ssh /storage/.config/distribution/configs/distribution.conf /storage/.config/emulationstation/es_settings.cfg /storage/.cache/shadow /storage/.cache/ssh /storage/.cache/connman >${BPATH}/backup.log 2>&1
	if [ "${EMURESTART}" == true ]
	then
		systemctl start emustation
	fi
}

function clearconfig() {
	case "${1}" in
	"EMUS")
		systemctl stop emustation
		/usr/bin/ee_backup.sh b no
		find /storage -mindepth 1 \( ! -regex '^/storage/.config/emulationstation/themes.*' -a ! -regex '^/storage/.update.*' -a ! -regex '^/storage/download.*' -a ! -regex '^/storage/roms.*' \) -delete
		mkdir /storage/.config/
		sync
		small-cores enable
		systemctl reboot
	;;
        "retroarch")
                rm -f /storage/.config/retroarch/retroarch.cfg
                cp -rf /usr/config/retroarch/retroarch.cfg /storage/.config/retroarch/retroarch.cfg
        ;;
	"ALL")
		systemctl stop emustation
		cd /
		find /storage -mindepth 1 \( ! -regex '^/storage/.update.*' -a ! -regex '^/storage/roms.*' \) -delete
		mkdir /storage/.config/
		sync
		small-cores enable
		systemctl reboot
	;;
esac
}

function ee_backup() {
        BACKUPFILE="/storage/roms/backup/AmberELEC_BACKUP.zip"
        mkdir -p "/storage/roms/backup"

        case "${1}" in
        "restore")
                echo -en '\e[20;0H\e[37mPlease wait, restoring system...\e[0m' >/dev/console
                systemctl stop emustation
                unzip -o ${BACKUPFILE} -d /
                /usr/bin/postupdate.sh
                sleep 3
                systemctl start emustation
        ;;
        "backup")
                echo -en '\e[20;0H\e[37mPlease wait, backing up system...\e[0m' >/dev/console
                [ -f "${BACKUPFILE}" ] && rm "${BACKUPFILE}"
                [ -z "$2" ] && systemctl stop emustation
                zip -9 -r ${BACKUPFILE} \
                          /storage/.cache/bluetooth/* \
                          /storage/.cache/connman* \
                          /storage/.config/distribution/configs/distribution.conf \
                          /storage/.emulationstation/es_*.cfg \
                          /tmp/joypads/* \
                          /storage/.config/ppsspp/* \
                          /storage/.config/retroarch/* \
                          /storage/.emulationstation/scripts/*
                [ -z "${2}" ] && systemctl start emustation
        ;;
        esac
}

function setemu(){
## workaround for ES performance with big conf files
## This is no longer in use!

EE_CONF="/storage/.config/distribution/configs/emuoptions.conf"
[ ! -f "${EE_CONF}" ] && touch "${EE_CONF}"

	case "$1" in
	"set")
		PAT=$(echo "${2}" | sed -e 's|\"|\\"|g' | sed -e 's|\[|\\\[|g' | sed -e 's|\]|\\\]|g')
		sed -i "/^$PAT/d" "${EE_CONF}"
		S2="${2}"
		S3="${3}"
		shift 2
		if [ "${S3}" != "auto" ]; then
			[ "${S3}" == "disable" ] && echo "#${S2}=" >> "${EE_CONF}" || echo "${S2}=${@}" >> "${EE_CONF}"
		fi
		;;
	"get")
		PAT=$(echo ${2} | sed -e 's|\"|\\"|g' | sed -e 's|\[|\\\[|g' | sed -e 's|\]|\\\]|g' | sed -e 's|(|\\\(|g' | sed -e 's|)|\\\)|g')
		PAT="^${PAT}=(.*)"
		EES=$(cat "${EE_CONF}" | grep -oE "${PAT}")
		echo "${EES##*=}"
		;;
	*)
	echo "usage: emuelec-utils setemu [set get] value"
	esac
}

function getshaders() {
	find /tmp/shaders -name '*.glslp' -print0 |
		while IFS= read -r -d '' line; do
		echo ${line#/tmp/shaders/},
	done
}

function getfilters() {
	find /usr/share/retroarch/filters/video/ -name '*.filt' -print0 |
			while IFS= read -r -d '' line; do
			echo ${line#/usr/share/retroarch/filters/video/},
	done
}

function getip() {
IP="$(ifconfig wlan0 | grep 'inet addr' | cut -d: -f2 | awk '{print $1}')"

  if [ -z "$IP" ]; then
	 IP="$(ifconfig eth0 | grep 'inet addr' | cut -d: -f2 | awk '{print $1}')"
  fi

 if [ -z "$IP" ]; then
	echo "No Internet"
 else
	echo "${IP}"
	echo "${IP}" > /storage/ip.txt
 fi
}

function resolutions() {

	RESOLUTIONS=()

	# N2 supported resolutions source : https://wiki.odroid.com/odroid-n2/application_note/software/set_display_mode
	N2_SUPPORTED_RESOLUTIONS="480x320p60hz 640x480p60hz 720x480p60hz 720x576p50hz 800x480p60hz 1024x600p60hz 1024x768p60hz 1280x1024p60hz 1280x720p50hz 1280x720p60hz 1280x800p60hz 1360x768p60hz 1440x900p60hz 1600x1200p60hz 1600x900p60hz 1680x1050p60hz 1920x1080p24hz 1920x1080p30hz 1920x1080p50hz 1920x1080p60hz 1920x1200p60hz 2560x1080p60hz 2560x1440p60hz 2560x1600p60hz 3440x1440p60hz 3840x2160p24hz 3840x2160p25hz 3840x2160p30hz 3840x2160p50hz 3840x2160p60hz"

	# Screen supported resolutions
	SCREEN_SUPPORTED_RESOLUTIONS=`/usr/bin/cat /sys/class/amhdmitx/amhdmitx0/rawedid | /usr/bin/edid-decode |/usr/bin/grep "@" | sed -E "s| {0,9}VIC {0,9}[0-9]{1,2}||" | /usr/bin/awk '{print $1}' | /usr/bin/sed  's/@/p/g'|/usr/bin/tr '[:upper:]' '[:lower:]'`

	for N2SP in $N2_SUPPORTED_RESOLUTIONS
	do
	for SSR in $SCREEN_SUPPORTED_RESOLUTIONS
	do
		if [ "$N2SP" = "$SSR" ]
		then
		RESOLUTIONS+=($N2SP)
		fi
	done
	done

	IFS=","
	echo "${RESOLUTIONS[*]}"
}

function showdialog() {
	source /usr/bin/env.sh
	joy2keyStart

	[[ "${1}" == "Game" ]] && ERROR=$(cat /tmp/logs/exec.log) || ERROR="${2}"

	if [[ ! -z "${1}" ]] && [[ ! -z "${ERROR}" ]]; then
		if [ "$EE_DEVICE" == "OdroidGoAdvance" ] || [[ "$EE_DEVICE" =~ RG351 ]]; then
			dialog --backtitle 'AmberELEC Error' --title "${1} Error" --ascii-lines --colors --no-collapse --ok-label 'Close' --msgbox "${ERROR}" 20 35
		else
			dialog --backtitle 'AmberELEC Error' --title "${1} Error" --ascii-lines --colors --no-collapse --ok-label 'Close' --msgbox "${ERROR}" 30 80
		fi
	fi
}

function current_timezone() {
	readlink -f /etc/localtime | sed 's;/usr/share/zoneinfo/;;'
}

function timezones() {
	# cat /usr/share/zoneinfo/zone1970.tab | grep -v "^#" | awk '{ print $3 }' | sort -u | tr '\n' ','
	cat /usr/share/zoneinfo/zone1970.tab | grep -v "^#" | awk '{ print $3"," }' | sort -u
}

function small-cores() {
    if grep -q "g12b" /proc/device-tree/compatible; then
        case "$1" in
        "enable")
            echo "1" > /sys/devices/system/cpu/cpu0/online
            echo "1" > /sys/devices/system/cpu/cpu1/online
        ;;
        "disable")
            echo "0" > /sys/devices/system/cpu/cpu0/online
            echo "0" > /sys/devices/system/cpu/cpu1/online
        ;;
        esac
    fi
}

cmd=${1}
shift
$cmd "$@"

exit 0
